package com.leetcode;

/**
 * 最长回文子串
 * 给你一个字符串 s，找到 s 中最长的回文子串。
 *
 * @author winson
 * @create 2022-03-28 11:22
 */
public class LongestPalindromeSolution {

    /**
     * 通过中心扩展，往左右两边移动指针进行比较
     * @param s
     * @return
     */
    public String longestPalindrome(String s) {
        int length = s.length();
        int start = 0, end = 0;
        for (int i = 0; i < length; i++) {
            int end1 = expand(s, i, i);
            int end2 = expand(s, i, i + 1);
            // 对比返回回文字符串长度大小
            int len = Math.max(end1, end2);
            if (len > end - start) {
                /**
                 * 计算开始，结束位置
                 */
                start = i - (len - 1) / 2;
                end = i + len / 2;
            }
        }
        return s.substring(start, end + 1);
    }

    /**
     * 返回字符串长度
     * @param s
     * @param left
     * @param right
     * @return
     */
    public int expand(String s, int left, int right) {
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            left--;
            right++;
        }
        return right - left - 1;
    }

    public static void main(String[] args) {
        /**
         * 输入：s = "babad"
         * 输出："bab"
         * 解释："aba" 同样是符合题意的答案。
         *
         * 输入：s = "cbbd"
         * 输出："bb"
         */
        LongestPalindromeSolution solution = new LongestPalindromeSolution();
        String s1 = solution.longestPalindrome("babad");
        String s2 = solution.longestPalindrome("cbbd");
        System.out.println(".........");
    }

}
